<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" queryCode="userList"/>
 
    <TableHeader :can-collapsed="false">
      <template v-slot:left>
        <el-button
          type="primary"
          size="small"
          :icon="CirclePlus" 
           v-if="isShowed('user:add')"
          @click="onAddItem"
          >新增
        </el-button>
        <el-button
          type="danger"
          size="small"
          :icon="Delete"
          v-if="isShowed('user:delete')"
          @click="onDeleteItem(selectRows)"
          >删除
        </el-button>
      </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
            
            <el-tooltip effect="dark" content="刷新页面" placement="top">
              <el-button
                circle
                icon="RefreshIcon"
                size="small"
                @click="doRefresh"
              />
            </el-tooltip>
            
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    />
   
  <Dialog ref="dialog"  :width="540" title="编辑信息" :form-items="formItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="formItems"
        >
         <template #prefix>
            <el-form-item :label="departmentFormItem.label">
              <TreeSelector
                v-model:value="departmentFormItem.value"
                placeholder="请选择所属部门"
                :data="departmentFormItem.values"
                :dataFields="{
                  label: 'departmentName',
                  value: 'departmentOid',
                }"
              />
            </el-form-item>
          </template>
        </BaseForm>
      </template>
  </Dialog>

  <Dialog ref="passDialog"  :width="380" title="修改密码" :form-items="passFormItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="passFormItems"
        ></BaseForm>
      </template>
  </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import {Md5} from "ts-md5/dist/md5";
import { ElMessage } from 'element-plus';
import {computed,onMounted, reactive, ref } from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryUserList,saveUser,updateUser,deleteBatchUser,findDepartmentList,checkPerms} from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import { isShowed } from '@/utils/index';
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { each } from 'lodash';
import { depArraytotree} from "@/utils/index";
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableColumns = reactive([
  { label: "用户名", 
    prop: "userName", 
  },
  { label: "真实姓名", 
    prop: "realName", 
    // checked:true,
  },
  { label: "所属部门", 
    prop: "departmentName", 
  },
  { label: "性别", 
    prop: "sex", 
    type: "Render",
    render: (h: any, { sex }: any) => {
      if (sex === "F") {
        return <el-button type="text">女</el-button>;
      }
      if (sex === "M") {
        return <el-button type="text">男</el-button>;
      }
      return <el-button type="text">男</el-button>;
    },
  },
  { label: "手机号", 
    prop: "mobileNo", 
  },
 
  { label: "进入日期", 
    prop: "enterDate", 
    type: "Render",
    render: (h: any, { enterDate }: any) => {
      if (enterDate !== null) {
        return new Date(enterDate).toLocaleDateString();
      }else{
        return '';
      }
    },
    
  },
  // { label: "QQ", 
  //   prop: "qqNo", 
  //   checked:true,
  // },
  { label: "邮箱", 
    prop: "email", 
  },
  { label: "微信号", 
    prop: "wechatNo", 
  },
  { label: "身份证号", 
    prop: "identificationNo", 
  },
  { label: "籍贯", 
    prop: "nativePlace",
  },
  { label: "在职状态", 
    prop: "state", 
    type: "Render",
    render: (h: any, { state }: any) => {
      if (state === "I") {
        return <el-button type="text">在职</el-button>;
      }
      if (state === "E") {
        return <el-button type="text">离职</el-button>;
      }
      return <el-button type="text">在职</el-button>;
    },
  },
  { label: "年龄", 
    prop: "age", 
  },

]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    code: "user:edit",
    isShow:true,
    handler: (row: any) => handleEdit(row),
  },
   {
    text: "修改密码",
    key: "edit1",
    type: "danger",
    code: "user:edit",
    isShow:true,
    handler: (row: any) => handleEditPass(row),
  },
]);

const departmentFormItem = reactive({
    label: "所属部门", 
    type: 'select',
    name: "departmentOid", 
    value: 0,
    hidden: true,
    placeholder: '请选择部门信息',
    selectOptions: {} ,
    values:{},
    reset() {
                this.value = 0;
            },
});

const passwordItem = reactive({
    label: '密码', 
    type: 'input',
    name: "password",
    inputType: 'password',
    value: '',
    placeholder: '请输入密码',
    validator: (item: any) => {
        if (!item.value) {
            ElMessage.error(item.placeholder);
            return false;
        }
        return true;
    }, 
    reset() {
        this.value = "";
    },
});

const formItems = reactive([
  { label: "", 
    type: 'input',
    name: "versionNo", 
    hidden: true,
    value: '',
    reset() {
                this.value = "";
            },
  },
  { label: '', 
    type: 'input',
    name: "userOid",
    hidden: true, 
    value: '',
    reset() {
                this.value = "";
            },
  },
  
   { label: "用户名", 
    type: 'input',
    name: "userName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入用户名信息',
    validator: (item: any) => {
            if (!item.value) {
                ElMessage.error(item.placeholder);
                return false;
            }
            return true;
        }, 
    reset() {
                this.value = "";
            },
  },
 
  { label: "真实姓名", 
    type: 'input',
    name: "realName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  passwordItem,
  departmentFormItem,
  { label: "性别", 
    type: 'radio-group',
    name: "sex", 
    value: "F",
    maxlength: 20,
    placeholder: '请选择性别信息',
    radioOptions:[
      {
        label: "女",
        value: "F",
      },
      {
        label: "男",
        value: "M",
      },
    ],
    reset() {
                this.value = "M";
            },
  },
  { label: "手机号", 
    type: 'input',
    name: "mobileNo", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  { label: "邮箱", 
    type: 'input',
    name: "email", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  { label: "微信号", 
    type: 'input',
    name: "wechatNo", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  { label: "进入日期", 
    type: 'date',
    name: "enterDate", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  { label: "身份证号", 
    type: 'input',
    name: "identificationNo", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
  { label: "籍贯", 
    type: 'input',
    name: "nativePlace", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    reset() {
                this.value = "";
            },
  },
   { label: "在职状态", 
    type: 'select',
    name: "state", 
    value: '',
    maxlength: 20,
    placeholder: '请输入信息',
    selectOptions: [
      {
        label: "在职",
        value: "I",
      },
        {
        label: "离职",
        value: "E",
      },
    ],
    reset() {
                this.value = "";
            },
  },
  { label: "年龄", 
    type: 'number',
    name: "age", 
    value: 18,
    maxlength: 20,
    placeholder: '请输入年龄信息',
    reset() {
                this.value = 18;
            },
  },

]);

const passFormItems = reactive([
  { label: "versionNo", 
    type: 'input',
    name: "versionNo", 
    hidden: true,
    value: 0,
    reset() {
                this.value = 0;
            },
  },
  { label: 'userOid', 
    type: 'input',
    name: "userOid",
    hidden: true, 
    value: 0,
    reset() {
                this.value = 0;
            },
  },
  passwordItem,
  
]);
const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const passDialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
let departmentResultList: any = [] ;

function handleEdit(data: any) {
  onUpdateItem(data);
}
function handleEditPass(data: any) {
  onUpdatePassItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propName = item[it.name];
    it.value = propName;
  });
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      passwordItem.value = Md5.hashStr(passwordItem.value);
      submitForm(updateUser,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
  });
};

const onUpdatePassItem = (item: any) => {
  passFormItems.forEach((it) => {
    const propName = item[it.name];
    it.value = propName;
  });
  passDialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (passDialog.value as any).loading = true;
    setTimeout(() => {
      passwordItem.value = Md5.hashStr(passwordItem.value);
      submitForm(updateUser,baseForm.value?.generatorParams())
      passDialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
   let params = {
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryUserList,params);
}

function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveUser,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
  if (data.length > 0) {
    showConfirmBox("是否要删除此数据项，删除后不恢复？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let params: number[] = [];
        data.forEach((item: { userOid: any }) => {
          params.push(item.userOid);
        });
        post({
          url: deleteBatchUser,
          data: {
            keyOids: params,
          },
        })
          .then(() => {
            doRefresh();
            showSuccessMessage("删除成功");
          })
          .catch(console.log);
      })
      .catch(() => {
        showInfoMessage("取消删除");
      });
  } else {
    showErrorMessage("请选择要删除的数据项");
  }
}

function searchForm(data: any) {
    let params = {
    searchConditionVOList: data,
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryUserList,params);
}

function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}


function findDepartment() {
  post({
    url: findDepartmentList,
    data: {     
    },
  })
  .then((res: any) => {
    departmentResultList = res.data;
    let allDdepartments= depArraytotree(res.data);
    departmentFormItem.values = allDdepartments;
    // tableConfig["tree"] = {rowKey:"departmentOid",child:allDdepartments}   
  })
  .catch(console.log);
}

departmentFormItem.selectOptions = computed(() => {
  return departmentResultList.map((it: any) => {
    return {
      label: it.departmentName,
      value: it.departmentOid,    
    };
  });
});

onMounted(doRefresh);
onMounted(findDepartment);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
